//
//  KABillDetailModel.swift
//  kano
//
//  Created by Frank on 2024/9/20.
//

import KakaJSON

class KABillDetailSubLoans: Convertible {
    //index
    var primaryIndex: Int = 0
    //leftAmount  贷款金额
    var remainingFunds: Double = 0.00
    //loanLeftAmount 待还金额
    var registrationConfirmation: Double = 0.00
    //subLoanAmount
    var subLoanQuantum: Double = 0.00
    //overdueFee 逾期手续费
    var validationCode: Double = 0.00
    //fee 手续费
    var chargeFee: Double = 0.00
    //repaymentAmount 还款金额
    var businessProcessType: Double = 0.00
    //repaymentTime 还款时间
    var examQuestionsSubject: TimeInterval = 0
    //dueTime 过期日期
    var dueDateTime: TimeInterval = 0
    //exceedDays 过期多少天
    var overdueDuration: Int = 0
    //repaymentStatus
    var emailProvider: Int = 0
    //还款详情页，手动选择账单时用于标识选中状态
    var select: Bool = false
    
    //gid
    var uniqueIdentifier: String = ""
    //subRate
    var subLoanInterestRate: Double = 0.00

    required init() {}
    init(primaryIndex: Int, uniqueIdentifier: String = "", remainingFunds: Double, registrationConfirmation: Double, subLoanQuantum: Double, validationCode: Double, chargeFee: Double, subLoanInterestRate: Double = 0.00, businessProcessType: Double, examQuestionsSubject: TimeInterval = 0, dueDateTime: TimeInterval, overdueDuration: Int, emailProvider: Int, select: Bool = false) {
        self.primaryIndex = primaryIndex
        self.uniqueIdentifier = uniqueIdentifier
        self.remainingFunds = remainingFunds
        self.registrationConfirmation = registrationConfirmation
        self.subLoanQuantum = subLoanQuantum
        self.validationCode = validationCode
        self.chargeFee = chargeFee
        self.subLoanInterestRate = subLoanInterestRate
        self.businessProcessType = businessProcessType
        self.examQuestionsSubject = examQuestionsSubject
        self.dueDateTime = dueDateTime
        self.overdueDuration = overdueDuration
        self.emailProvider = emailProvider
        self.select = select
    }
}

class KAReduceResult: Convertible {
    //loanGid
    var loanTransactionIdentifier: String = ""
    //shouldShow
    var shortLinkIndicator: Bool = false
    //beforeOverDueFee
    var unpaidCount: Int = 0
    //reduceFee
    var displayOption: Int = 0
    required init() {}
}

class KABillDetailModel: Convertible {
    //借款协议中，展示分期还款日期（自定义字段）
    var dueDateArr: [TimeInterval] = []
    // creditAddress 授信地址（借款协议用）
    var productIdentifier: String = ""
    //userName 用户名（借款协议用）
    var optOutURL: String = ""
    //贷款金额 loanAmount
    var overdueStatus : Double = 0.00
    //fee 手续费
    var chargeFee : Double = 0.00
    //interest 利息
    var voucherIdentifier : Double = 0.00
    //overdueFee 逾期费用
    var validationCode: Double = 0.00
    //repaymentAmount 还款金额
    var businessProcessType : Double = 0.00
    //loanLeftAmount 待还金额
    var registrationConfirmation: Double = 0.00
    //loanStatus 0: 借款失败 1:已还款 2:还款失败 3:打款中 4: 待还款 5:已逾期 8:借款成功，等待打款 9:审核中
    var loanCondition: Int = 0
    //dueTime 过期日期
    var dueDateTime: TimeInterval = 0
    //exceedDays 过期天数
    var overdueDuration: Int = 0
    //loanTime 贷款时间
    var loanTimeline : TimeInterval = 0
    //loanType 贷款类型
    var maximumLoanLimit: Int = 0
    //subLoanCount 分期数量
    var secondaryLoanTotal: Int = 0
    //withdrawCardNo 银行卡号
    var withdrawalCardNumber: String = ""
    //orderNo 账单
    var orderSequenceNumber: String = ""
    //loanPeriod 贷款天数
    var loanDuration: Int = 0
    //status  0：打款中，2：还款处理中--7/20续期中，9：审核中, 8：因网络原因借款失败 99：因没有获取到绑卡token而借款失败,   1、4 ：待还款
    var operationalStatus: Int = 0
    //subLoans 大额分期账单，蝌蚪贷手动拆分订单
    var transactionUserType : [KABillDetailSubLoans]?
    //repaymentVouchers 还款凭证，还没用上
    var repaymentDiscounts : [KABillDetailSubLoans]?
    //tadpoleLoanFlag 是否是蝌蚪贷订单
    var tadpoleLoanIndicator: Bool = false
    //tadpoleLoanLeftAmount 蝌蚪贷 待还金额
    var remainingLoanBalance: Double = 0.00
    //eachPeriod 蝌蚪贷"14|346"数据分离
    var voucherSta: String = ""
    //repayRatio 蝌蚪贷每期利率
    var repaymentRatio: String = ""
    //拆分蝌蚪贷时间时手动记录，用于逾期账单计算利息使用
    var firstPeriod: Int = 0
    
    var feeReductionf: Int = 0
    var largeSubLoanInfo: [KAReduceResult]?
    var validityExpiration: TimeInterval = 0
    var transactionProcessingSum: Int = 0
    var currentDateTime: TimeInterval = 0
    var renewalDeadline: TimeInterval = 0
    var configuredSubVouchers: String = ""
    var contactNumber: String = ""
    var renewalAmount: Int = 0
    var renewalCapabilityr: Bool = false
    var responseContent: Int = 0
    var repaymentstate: Int = 0
    var newPassphrase: Int = 0
    var originSource: Int = 0
    var initialAuthFlag: Int = 0
    var lastRepaymentFailureTime: TimeInterval = 0
    var validityLimit: Int = 0
    var ongoingRepaymentStatus : Int = 0
    var transactionDateTime: TimeInterval = 0
    var taxAmount: Int = 0
    var overdueQuantity: Int = 0
    
    
    required init() {}
    
    func kj_didConvertToModel(from json: [String : Any]) {
        if tadpoleLoanIndicator {
            //手动分成两期
            secondaryLoanTotal = 2
            loanDuration = 360
            
            //"14|346"数据分离
            let eachPeriodArray = voucherSta.components(separatedBy: "|")
            let repayRatioArray = repaymentRatio.components(separatedBy: "|")
            //string to int
            let splitPeriod = eachPeriodArray.compactMap { Int($0) }
            let splitRatio = repayRatioArray.compactMap { Double($0) }
            
            //如果tadpoleLoanLeftAmount有值直接用，没值手动计算
            var leftAmount = remainingLoanBalance != 0 ? Double(remainingLoanBalance) : (Double(overdueStatus) * splitRatio[0])
            
            firstPeriod = splitPeriod[0]
            //计算蝌蚪贷分期
            var list: [KABillDetailSubLoans] = []
            list.append(KABillDetailSubLoans(primaryIndex: 1,
                                             remainingFunds: Double(Int(leftAmount)),
                                             registrationConfirmation: Double(leftAmount),
                                             subLoanQuantum: Double(leftAmount) - chargeFee,
                                             validationCode: validationCode,
                                             chargeFee: chargeFee,
                                             businessProcessType: loanCondition == 1 ? Double(leftAmount) : businessProcessType,
                                             dueDateTime: loanTimeline + TimeInterval((splitPeriod[0]-1) * 86400),
                                             overdueDuration: overdueDuration,
                                             emailProvider: loanCondition == 1 ? 3 : 1
                                            ))
            
            leftAmount = Double(overdueStatus) * splitRatio[1]
            let days = splitPeriod[0] + splitPeriod[1] - 1
            list.append(KABillDetailSubLoans(primaryIndex: 2,
                                             remainingFunds: Double(leftAmount),
                                             registrationConfirmation: Double(leftAmount),
                                             subLoanQuantum: Double(leftAmount),
                                             validationCode: validationCode,
                                             chargeFee: chargeFee,
                                             businessProcessType: loanCondition == 1 ? Double(leftAmount) : businessProcessType,
                                             dueDateTime: loanTimeline + TimeInterval(days * 86400),
                                             overdueDuration: -1,
                                             emailProvider: loanCondition == 1 ? 3 : 1
                                            ))
            
            transactionUserType = list
        }
    }
    
    func ka_getDueDate() -> [TimeInterval] {
        //大额、蝌蚪贷
        if secondaryLoanTotal > 0 {
            let dueDateTime = transactionUserType!.map { $0.dueDateTime }
            return dueDateTime
        }
        else {
            return [dueDateTime]
        }
    }
    
    func ka_overDays() -> Int {
        if secondaryLoanTotal > 0 && !tadpoleLoanIndicator {
            for subLoan in transactionUserType! {
                if subLoan.emailProvider != 3 {
                    return subLoan.overdueDuration
                }
            }
            return 0
        } else {
            return overdueDuration
        }
    }
    
    //是否逾期
    func ka_hasOverDueBill() -> Bool {
        //大额，1、遍历找到未还清款账单 2、判断该账单是否已逾期
        if secondaryLoanTotal > 0 && !tadpoleLoanIndicator {
            for subLoan in transactionUserType! {
                if subLoan.emailProvider != 3 {
                    return subLoan.overdueDuration > 0
                }
            }
            return false
        }
        //蝌蚪贷、小额，直接用外部逾期天数判断即可
        else {
            return overdueDuration > 0
        }
    }
    
    func ka_isDueTodayUnpay() -> Bool {
        if secondaryLoanTotal > 0 && !tadpoleLoanIndicator {
            for subLoan in transactionUserType! {
                if subLoan.emailProvider != 3 {
                    return subLoan.overdueDuration == 0 && subLoan.emailProvider != 3
                }
            }
            return false
        } else {
            return overdueDuration == 0 && loanCondition != 1
        }
    }
}

